#include "gd32f30x.h"
#include "stdint.h"
#include "stdio.h"
#include "stdlib.h"
#include "cpuusage.h"

#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"

#include "DevicesDelay.h"
#include "DevicesADC.h"
#include "DevicesKey.h"
#include "DevicesLed.h"
#include "DevicesQueue.h"
#include "DevicesSPI.h"
#include "DevicesSPIFlash.h"
#include "DevicesTimer.h"
#include "DevicesUart.h"
#include "DevicesWatchDog.h"
#include "DevicesSoftTimer.h"
#include "DevicesTime.h"
#include "DevicesWatchDog.h"
#include "DevicesUID.h"

#include "usb_user.h"
#include "stm32_eval_spi_sd.h"
#include "DriverFile.h"
#include "DriverLcd.h"
#include "DriverMenu.h"
#include "DriverFont.h"
#include "NesSystem.h"

#include "taskSoftTimer.h"
#include "taskNes.h"
#include "taskKey.h"
#include "taskMessageSlave.h"
#include "taskSystem.h"


TaskHandle_t g_TaskSystemInitHand = NULL;  /* 系统初始化任务句柄 */

/* SPI Flash 读、写互斥信号量 */
SemaphoreHandle_t g_xSpiFlashSemaphore;
SemaphoreHandle_t g_xFileSemaphore;


void vApplicationIdleHook( void )
{
    /* CPU占用率计算 */
    vCPUUsageIdleHook();

    /* 喂狗 */
    vWatchdogReload();
}

void vUserSystemInit(void)
{
    enumQueueInit();

    cTimer2Init();

    vLedInit();

    vSPIFlashInit();

    SD_Init();

    vLcdInit();

    if((uiKeyValueGet() & KEY_UP) != 0)
    {
        vUsbInit();
    }
    else
    {
        cFileInit();

        cFontInit();

        /* 读取SD卡内壁纸文件 */
        cLcdDesktopInit();
    }

    cLcdDesktopShow();

    cSoftTimerInit();

//    vWatchdogInit();
}

void vTaskSystemInit(void *pvParameters)
{
    NesInfoType *ptyeNesInfo = ptyeNesInfoGet();

    printf("FreeRTOS start succeed...\r\n");

    /* 创建递归互斥信号量 */
    g_xSpiFlashSemaphore = xSemaphoreCreateRecursiveMutex();
    g_xFileSemaphore = xSemaphoreCreateRecursiveMutex();

    vKeyInit();


//    xTaskCreate(vTaskKey,               "Key",              256,    NULL, configMAX_PRIORITIES - 2, &g_TaskKeyHand);

//    xTaskCreate(vTaskMessageSlave,      "Message Slave",    512,    NULL, configMAX_PRIORITIES - 3, &g_TaskMessageSlaveHand);

    vDelayMs(1000);


    vUserSystemInit();

    printf("SystemInit succeed.\r\n");


    if((uiKeyValueGet() & KEY_UP) != 0)
        vTaskDelete( NULL );


    while(1)
    {
        cMenuInit();

        vTaskDelay(50);

        /* 退出选项 */
        if(ptyeNesInfo->runing != 0)
            break;
    }


    /* 清屏 */
    vLcdClear(0, 0, 320, 240, BLACK);


    xTaskCreate(vTaskNes,               "Nes",              1024,    NULL, configMAX_PRIORITIES - 6, &g_TaskNesHand);


    /* 删除自己 */
    vTaskDelete( NULL );
}
